﻿using System;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Jacky
{
    /// <summary>
    /// 长按事件
    /// </summary>
    public class LongPressButton : MonoBehaviour, IPointerDownHandler,IPointerUpHandler
    {

        private float _judgeTime = CommonConfig.LongPressTime;

        private float _calTime = 0;

        private bool _isDown = false;

        private bool _isTriggerEvent = false;

        public Action LongPressEvent;
        
        public void OnPointerDown(PointerEventData eventData)
        {
            _isDown = true;
        }

        private void Update()
        {
            if (_isTriggerEvent)
            {
                return;
            }

            if (_isDown)
            {
                _calTime += Time.unscaledDeltaTime;
                if (_calTime >= _judgeTime)
                {
                    LongPressEvent?.Invoke();
                    _isTriggerEvent = true;
                    Debug.Log("触发长按事件");
                }
            }
        }

        public void OnPointerUp(PointerEventData eventData)
        {
            _isDown = false;
            Reset();
        }

        private void Reset()
        {
            _calTime = 0;
            _isTriggerEvent = false;
            _isDown = false;
        }

        public void Dispose()
        {
            Reset();
            LongPressEvent = null;
        }
    }
}